//
//  CWebViewController.m
//  WeCommunity
//
//  Created by mac on 2017/8/8.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "CWebViewController.h"

#import <WebKit/WKBackForwardList.h>
#import <WebKit/WKWebView.h>
#import <WebKit/WKNavigationDelegate.h>
#import <WebKit/WKUIDelegate.h>
#import <WebKit/WKWebViewConfiguration.h>
#import <WebKit/WKUserContentController.h>
#import <WebKit/WKScriptMessage.h>
#import <WebKit/WKScriptMessageHandler.h>
#import <WebKit/WKUserScript.h>
#import <WebKit/WKNavigationResponse.h>


@interface CWebViewController ()<WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView * webView;
@property (nonatomic,strong) UIProgressView * progress;
@property (nonatomic,assign) BOOL addObserver;
@property (nonatomic,strong) UIBarButtonItem * backItem;
@property (nonatomic,strong) UIBarButtonItem * closeItem;

@end

@implementation CWebViewController

#pragma mark - get
-(UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backItem"] style:UIBarButtonItemStylePlain target:self action:@selector(processBackItem)];
    }
    return _backItem;
}

-(UIBarButtonItem *)closeItem
{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"close"] style:UIBarButtonItemStylePlain target:self action:@selector(processCloseItem)];
    }
    return _closeItem;
}

-(WKWebView *)webView
{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)- 64 )];
        [_webView setNavigationDelegate:self];
        [_webView setAutoresizesSubviews:YES];
        [_webView.scrollView setAlwaysBounceVertical:YES];
        // 这行代码可以是侧滑返回webView的上一级，而不是跟控制器（对侧滑有效）
        [_webView setAllowsBackForwardNavigationGestures:YES];
        _webView.backgroundColor = [UIColor whiteColor];
        
        //监听进度
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew  context:nil];
        //获取标题
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return _webView;
}
-(UIProgressView *)progress
{
    if (!_progress) {
        _progress = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0,KScreen_Width, 8)];
        _progress.progressTintColor = TINT_GREEN_COLOR;
        _progress.trackTintColor = [UIColor clearColor];
        _progress.progress = 0;
    }
    return _progress;
}

-(void)dealloc
{
    if (self.webView) {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
        [self.webView removeObserver:self forKeyPath:@"title"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configLinkUrl];
    
    [self initWithUserInterface];
    
    [self startLoadRequest];
}

-(void)initWithUserInterface
{
    self.title = KNSLocal(@"loadding");
    
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progress];
}

-(void)configLinkUrl
{
    if (![self.linkUrl.lowercaseString hasPrefix:@"https://"] && ![self.linkUrl.lowercaseString hasPrefix:@"http://"]) {
        self.linkUrl = [NSString stringWithFormat:@"http://%@",self.linkUrl];
    }
}

-(void)startLoadRequest
{
    NSURL * url = [NSURL URLWithString:[self.linkUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

#pragma mark - 获取进度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        [self.progress setProgress:[change[@"new"] floatValue] animated:YES];
        
        if ([change[@"new"] floatValue] == 1.0) {
            dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC);
            dispatch_after(time,dispatch_get_main_queue(), ^{
                [self.progress setProgress:0.0 animated:NO];
            });
        }
    }else if ([keyPath isEqualToString:@"title"])
    {
        [self setupNavcTitle];
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark -设置title
-(void)setupNavcTitle
{
    if (self.webView.title.length > 0) {
        self.navigationItem.title = self.webView.title;
    }
}

#pragma mark - 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"webVie开始加载：%@",webView.URL.absoluteString);
}

#pragma mark - 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    
    if (self.webView.backForwardList.backList.count == 0) {
        self.navigationItem.leftBarButtonItems = @[self.backItem];
    }else{
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        self.navigationItem.leftBarButtonItems = @[self.backItem,self.closeItem];
    }
    
    NSLog(@"webVie结束加载：%@",webView.URL.absoluteString);
}

#pragma mark - 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error
{
    [self.progress setProgress:0.0 animated:NO];
    
    if([error code] == NSURLErrorCancelled ||
       [error code] == 102 ||
       [error code] == NSURLErrorUnsupportedURL)  {
        return;
    }
    [self sureAlertWithTitle:nil andMesg:[error localizedDescription]];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error
{
    [self.progress setProgress:0.0 animated:NO];
    
    if([error code] == NSURLErrorCancelled ||
       [error code] == 102 ||
       [error code] == NSURLErrorUnsupportedURL)  {
        return;
    }
    [self sureAlertWithTitle:nil andMesg:[error localizedDescription]];
}

// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
//JavaScript调用alert方法后回调的方法 message中为alert提示的信息 必须要在其中调用completionHandler()
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    completionHandler();
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    UIApplication *application = [UIApplication sharedApplication];
    NSURL * url = webView.URL;
    if ([url.scheme isEqualToString:@"tel"])
    {
        if ([application canOpenURL:url])
        {
            decisionHandler(WKNavigationActionPolicyCancel);
            [application openURL:url];
            return;
        }
    }
    if ([url.absoluteString containsString:@"itunes.apple.com"])
    {
        if ([application canOpenURL:url])
        {
            decisionHandler(WKNavigationActionPolicyCancel);
            [application openURL:url];
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - webview 返回上一级页面
-(void)processBackItem
{
    WKBackForwardList * list = self.webView.backForwardList;
    if (list.backItem) {
        [self.webView goToBackForwardListItem:list.backItem];
    }else{
        [self processCloseItem];
    }
}

#pragma mark - 关闭
-(void)processCloseItem
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
